# -*- coding: utf-8 -*-
import BeautifulSoup
import re
import os
import copy
import sys


class XPFaceUtil:
    _pageConfigFile = ""
    _templatePath = ""
    _uiModulesPath = ""
    _soup = ""
    def __init__(self, filename, configFile, templatePath, uiModulesPath):
        XPFaceUtil._pageConfigFile = configFile
        XPFaceUtil._templatePath = templatePath
        XPFaceUtil._uiModulesPath = uiModulesPath
        #read tpl file and BeautifulSoup it
        file = open(filename, "r")
        tmpFileContent = file.read()
        XPFaceUtil._soup = BeautifulSoup.BeautifulSoup(tmpFileContent)
        #print XPFaceUtil._soup.contents[0].head
        file.close()
        
    #template file
    def genTemplate(self):
        tmpSoup = copy.deepcopy(XPFaceUtil._soup)
        foundTags = XPFaceUtil._getRegionSoups(tmpSoup)
        for foundTag in foundTags:
            moduleTags = XPFaceUtil._getUIModuleSoups(foundTag)
            replacedTag = False
            for moduleTag in moduleTags:
                if replacedTag:
                    moduleTag.replaceWith("")
                else:
                    moduleTag.replaceWith("<?php XPFace::getRegion(\""+ foundTag["id"] +"\");>")
                    replacedTag = True
                
        #XPFaceUtil._parseIf(tmpSoup)
        #XPFaceUtil._parseForeach(tmpSoup)
        templateFile = XPFaceUtil._templatePath + "/" + XPFaceUtil._getTemplateId() + ".tpl"
        if os.path.isfile(templateFile) == True:
            #print "The template id '" + XPFaceUtil._getTemplateId() + "' file is exists."
            commandInput = raw_input("The template id '" + XPFaceUtil._getTemplateId() + "' file is exists."+' Do you want to overwrite it? (y/n): ')
            if commandInput != "y":
                return
        file = open(templateFile, "w")
        file.write(tmpSoup.prettify())
        file.close()
            
        

    @classmethod
    def _getTemplateId(cls):
        # get the template id
        foundTag = XPFaceUtil._soup.find("html")
        return foundTag["id"]

    #page config file xml
    def genPageConfig(self):
        if os.path.isfile(XPFaceUtil._pageConfigFile) == False:
            file = open(XPFaceUtil._pageConfigFile, "w")
            file.write("<?xml version=\"1.0\" encoding=\"utf8\"?><pages></pages>")
            file.close()
        #init BeautifulStoneSoup
        file = open(XPFaceUtil._pageConfigFile, "r")
        pagesxmlSoup = BeautifulSoup.BeautifulStoneSoup(file.read())
        file.close()
        
        pageNode = pagesxmlSoup.find('page', {"id" : XPFaceUtil._getPageId()})
        #The page id is exists in the pages config xml file.
        if pageNode != None:
            #print "The page id '" + XPFaceUtil._getPageId() + "' is exists in the pages config."
            commandInput = raw_input("The page id '" + XPFaceUtil._getPageId() + "' is exists in the pages config."+' Do you want to overwrite it? (y/n): ')
            if commandInput != "y":
                return
            #update
            regionNodes = pageNode.findAll("region")
            for regionNode in regionNodes:
                regionNode.replaceWith("")
            regionSoups = XPFaceUtil._getRegionSoups(XPFaceUtil._soup)
            for regionSoup in reversed(regionSoups):
                #add region mode to config xml file
                XPFaceUtil._addRegionNode(pageNode, regionSoup)
            #write to file
            file = open(XPFaceUtil._pageConfigFile, "w")
            file.write(pagesxmlSoup.prettify())
            file.close()
            return
            
        #add new page
        #get root pages node
        pagesNodeSoup = pagesxmlSoup.find('pages')
        #add insert the page node
        pageNodeSoup = XPFaceUtil._addPageNode(pagesNodeSoup)
        #get region soups by html file.
        regionSoups = XPFaceUtil._getRegionSoups(XPFaceUtil._soup)
        
        #foreach the html region soups
        for regionSoup in reversed(regionSoups):
            #add region mode to config xml file
            xmlRegionNode = XPFaceUtil._addRegionNode(pageNodeSoup, regionSoup)
            
        file = open(XPFaceUtil._pageConfigFile, "w")
        file.write(pagesxmlSoup.prettify())
        file.close()
        

    @classmethod
    def _getPageId(cls):
        # get the page id
        foundTag = XPFaceUtil._soup.find("body")
        return foundTag["id"]

    @classmethod
    def _addPageNode(cls, pagesNodeSoup):
        emptySoup = BeautifulSoup.BeautifulSoup()
        pageNodeSoup = BeautifulSoup.Tag(emptySoup, "page")
        pageNodeSoup["id"] = XPFaceUtil._getPageId()
        pageNodeSoup["template"] = "templates/" + XPFaceUtil._getTemplateId() + ".tpl"
        pagesNodeSoup.insert(0, pageNodeSoup)
        return pageNodeSoup

    @classmethod
    def _addRegionNode(cls, pageNodeSoup, regionSoup):
        #get uimodule soups by html region soup.
        uiModuleSoups = XPFaceUtil._getUIModuleSoups(regionSoup)
        emptySoup = BeautifulSoup.BeautifulSoup()
        #region node
        regionNodeSoup = BeautifulSoup.Tag(emptySoup, "region")
        regionNodeSoup["id"] = regionSoup["id"]
        regionNodeSoup["uimodule"] = "uimodules/" + uiModuleSoups[0]["id"] + ".tpl"
        pageNodeSoup.insert(0, regionNodeSoup)
        return regionNodeSoup

    @classmethod
    def _addUIModuleNode(cls, xmlRegionNode, uiModuleId):
        emptySoup = BeautifulSoup.BeautifulSoup()
        xmlUIModuleNode = BeautifulSoup.Tag(emptySoup, "uimodule")
        xmlUIModuleNode["data-source-id"] = uiModuleId
        xmlUIModuleNode["template"] = "uimodules/" + uiModuleId + ".tpl"
        xmlRegionNode.insert(0, xmlUIModuleNode)
        return xmlUIModuleNode


    #uimodule files
    def genUIModules(self):
        tmpSoup = copy.deepcopy(XPFaceUtil._soup)
        #get all uimodule soups
        uiModuleSoups = XPFaceUtil._getUIModuleSoups(tmpSoup)
        for uiModuleSoup in uiModuleSoups:
            #XPFaceUtil._parseIf(uiModuleSoup)
            #XPFaceUtil._parseForeach(uiModuleSoup)
            XPFaceUtil._genUIModule(uiModuleSoup)
            
        """"""

    @classmethod
    def _genUIModule(cls, uiModuleSoup):
        uiModuleFile = XPFaceUtil._uiModulesPath + "/" + uiModuleSoup["id"] + ".tpl"
        if os.path.isfile(uiModuleFile) == True:
            #print "The uiModule id '" + uiModuleSoup["id"] + "' is exists."
            commandInput = raw_input("The uiModule id '" + uiModuleSoup["id"] + "' file is exists."+' Do you want to overwrite it? (y/n): ')
            if commandInput != "y":
                return
        file = open(uiModuleFile, "w")
        file.write(uiModuleSoup.prettify())
        file.close()

    @classmethod
    def _getRegionSoups(cls, tmpSoup):
        return tmpSoup.findAll("div", {"class" : re.compile("^region.*")})


    @classmethod
    def _getUIModuleSoups(cls, regionSoup):
        return regionSoup.findAll("div", {"class" : re.compile("^module.*")})
        

    @classmethod
    def _parseVar(cls, content):
        #replace the {$xxxx} tags
        content = re.sub("\{\$(\w*?)\}", r"<?php echo $\1>", content)
        content = re.sub("\{\$(\w*?)\.(\w*?)\}", r"<?php echo $\1->\2>", content)
        content = re.sub("\{\$(\w*?)\.(\w*?)\.(\w*?)\}", r"<?php echo $\1->\2->\3>", content)
        content = re.sub("\{\$(\w*?)\.(\w*?)\.(\w*?)\.(\w*?)\}", r"<?php echo $\1->\2->\3->\4>", content)
        return content


    @classmethod
    def _parseIf(cls, uiModuleSoup):
        #get if soups
        ifSoups = uiModuleSoup.findAll(attrs={'if' : re.compile(".*")})
        #print "\n1111111111111111111111111\n"
        for ifSoup in reversed(ifSoups):
            #if have foreach parse it
            XPFaceUtil._parseForeach(ifSoup)
            
            #to php code
            #print "\n1111111111111111111111111\n"
            ifContent = re.sub("\.", r"->", ifSoup["if"])
            del(ifSoup["if"])
            ifCode = "<?php if (" + ifContent + "):?>" + ifSoup.prettify() + "<?php endif;?>"
            ifSoup.replaceWith(ifCode)
            

    @classmethod
    def _parseForeach(cls, uiModuleSoup):
        #get foreach soups
        foreachSoups = uiModuleSoup.findAll(attrs={'foreach' : re.compile(".*")})
        for foreachSoup in reversed(foreachSoups):
            #to php code
            foreachContent = re.sub("\.", r"->", foreachSoup["foreach"])
            del(foreachSoup["foreach"])
            foreachCode = "<?php foreach (" + foreachContent + "):?>"
            for child in foreachSoup.contents:
                foreachCode = foreachCode + child.__str__()
                child.replaceWith("")
            foreachCode += "<?php endforeach;?>"
            foreachSoup.contents[0].replaceWith(foreachCode)
            #foreachSoup.replaceWith("")
            


if __name__ == '__main__':
    #print sys.argv
    xpFace = XPFaceUtil(sys.argv[1])
    xpFace.genTemplate()
    xpFace.genPageConfig()
    xpFace.genUIModules()
    #something = raw_input('Enter text: ')
    #print something

